package com.dh.example.netty.util;

import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.WebSocketServerHandshaker;
import io.netty.util.Attribute;
import io.netty.util.AttributeKey;

/**
 * netty util
 *
 * @author yolo
 * @date 2024/03/14 13:01:58
 */

public class NettyUtil {

    public static AttributeKey<String> TOKEN = AttributeKey.valueOf("token");
    public static AttributeKey<String> CLIENT_TYPE = AttributeKey.valueOf("clientType");
    public static AttributeKey<String> IP = AttributeKey.valueOf("ip");
    public static AttributeKey<Long> USER_ID = AttributeKey.valueOf("userId");
    public static AttributeKey<WebSocketServerHandshaker> HAND_SHAKER_ATTR_KEY = AttributeKey.valueOf(WebSocketServerHandshaker.class, "HANDSHAKER");

    /**
     * 设置attr
     *
     * @param channel      频道
     * @param attributeKey 属性键
     * @param data         数据
     */
    public static <T> void setAttr(Channel channel, AttributeKey<T> attributeKey, T data) {
        Attribute<T> attr = channel.attr(attributeKey);
        attr.set(data);
    }

    /**
     * 获取属性
     *
     * @param channel      频道
     * @param attributeKey 属性键
     * @return {@code T}
     */
    public static <T> T getAttr(Channel channel, AttributeKey<T> attributeKey) {
        return channel.attr(attributeKey).get();
    }
}
